package t10086.WorkThread;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import t10086.Configure.ThreadPoolConfig;

import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class ThreadPoolManager {
    // 静态的唯一线程池实例
    private static ThreadPoolExecutor executorService;

    @Autowired
    public ThreadPoolManager(ThreadPoolConfig threadPoolConfig) {
        executorService = new ThreadPoolExecutor(
                    threadPoolConfig.getCorePoolSize(),
                    threadPoolConfig.getMaximumPoolSize(),
                    threadPoolConfig.getKeepAliveTime(),TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(threadPoolConfig.getMaxWaitedTasks())
            );
    }

    // 提交任务给线程池执行
    public static  Future<?> submitTask(Runnable task) {
        return executorService.submit(task);
    }

    // 关闭线程池
    public static synchronized void shutdown() {
        executorService.shutdown();
    }


    // 终止所有正在执行的任务以及等待队列中的任务，但保留线程池
    public static synchronized void terminateAllTasks() {
        // 先中断正在执行的任务
        List<Runnable> pendingTasks = executorService.shutdownNow();  // 会停止等待队列中的任务,给正则执行的任务添加中断标志

        // 输出尚未执行的任务数量
        System.out.println("尚未执行的任务数量: " + pendingTasks.size());

        // 如果任务实现了 Future，则可以调用 cancel(true) 来中断它们
        for (Runnable task : pendingTasks) {
            if (task instanceof Future<?>) {
                ((Future<?>) task).cancel(true);
            }
        }

        // 重新创建线程池，保持线程池服务
        executorService = new ThreadPoolExecutor(
                executorService.getCorePoolSize(),
                executorService.getMaximumPoolSize(),
                executorService.getKeepAliveTime(TimeUnit.SECONDS),
                TimeUnit.SECONDS,
                executorService.getQueue()
        );
    }

    // 提供当前线程池状态信息
    public static  String getPoolStatus() {
        return "Active Threads: " + executorService.getActiveCount() +
                ", Total Tasks: " + executorService.getTaskCount();
    }
}
